package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLog;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLogConstant;
import com.cskaoyan.wordmemorize.common.constant.ResultCodeEnum;
import com.cskaoyan.wordmemorize.common.exception.BusinessException;
import com.cskaoyan.wordmemorize.converter.VocBookConverter;
import com.cskaoyan.wordmemorize.dao.entity.VocBookDO;
import com.cskaoyan.wordmemorize.dao.entity.VocCategoryDO;
import com.cskaoyan.wordmemorize.dao.entity.VocChapterDO;
import com.cskaoyan.wordmemorize.dao.entity.VocDO;
import com.cskaoyan.wordmemorize.dao.mapper.VocBookMapper;
import com.cskaoyan.wordmemorize.dao.mapper.VocChapterMapper;
import com.cskaoyan.wordmemorize.dto.admin.DeleteBookOperateDTO;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.admin.VocBookDTO;
import com.cskaoyan.wordmemorize.request.BatchDeleteCommand;
import com.cskaoyan.wordmemorize.request.VocBookCommand;
import com.cskaoyan.wordmemorize.request.VocBookPageRequest;
import com.cskaoyan.wordmemorize.service.VocBookService;
import com.cskaoyan.wordmemorize.service.VocChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class VocBookServiceImpl implements VocBookService {

    @Autowired
    VocBookMapper vocBookMapper;

    @Autowired
    VocBookConverter vocBookConverter;

    @Autowired
    VocChapterMapper vocChapterMapper;

    @Autowired
    VocChapterService vocChapterService;

    @Override
    public PageDTO<VocBookDTO> getBookPage(VocBookPageRequest pageQuery) {

        if (pageQuery.getPageNum() == null) {
            LambdaQueryWrapper<VocBookDO> vocBookWrapper1 = new LambdaQueryWrapper<>();
            vocBookWrapper1.eq(pageQuery.getCategoryId()!=null,VocBookDO::getBcId,pageQuery.getCategoryId());
            List<VocBookDO> vocBookDOS = vocBookMapper.selectList(vocBookWrapper1);

            return vocBookConverter.vocBookList2Page(vocBookDOS, (long) vocBookDOS.size());
        }
        Page<VocBookDO> pageParam = new Page<>(pageQuery.getPageNum(), pageQuery.getCount());
        LambdaQueryWrapper<VocBookDO> vocBookWrapper = new LambdaQueryWrapper<>();
        vocBookWrapper.eq(pageQuery.getCategoryId()!=null,VocBookDO::getBcId,pageQuery.getCategoryId())
                .like(pageQuery.getKeyword() != null,VocBookDO::getName,pageQuery.getKeyword());
        Page<VocBookDO> vocBookDOPage = vocBookMapper.selectPage(pageParam, vocBookWrapper);

        return vocBookConverter.vocBookList2Page(vocBookDOPage.getRecords(),vocBookDOPage.getTotal());
    }

    @Override
    @OperateLog(dateType = "书籍", operateType = OperateLogConstant.OPERATE_ADD)
    public Long addVocBook(VocBookCommand command) {
        LambdaQueryWrapper<VocBookDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VocBookDO::getName,command.getName());

        VocBookDO vocBookDO = vocBookMapper.selectOne(queryWrapper);
        if(vocBookDO != null){
            throw new RuntimeException("书籍已存在");
        }
        VocBookDO vocBook = vocBookConverter.vocBookCommand2VocBookDO(command);
        vocBookMapper.insert(vocBook);
        return vocBook.getId();
    }

    @Override
    @OperateLog(dateType = "书籍", operateType = OperateLogConstant.OPERATE_UPDATE)
    public void updateVocBook(VocBookCommand command) {
        VocBookDO vocBook = vocBookConverter.vocBookCommand2VocBookDO(command);
        vocBook.setId(Long.valueOf(command.getId()));
        vocBookMapper.updateById(vocBook);
    }

    @Override
    @OperateLog(dateType = "书籍", operateType = OperateLogConstant.OPERATE_SINGLE_DELETE)
    public DeleteBookOperateDTO deleteVocBook(Long bookId) {
        VocBookDO vocBookDO = vocBookMapper.selectById(bookId);
        if(vocBookDO == null){
            throw new BusinessException(ResultCodeEnum.BOOK_OFFLINE);
        }
        deleteChapterByBookId(bookId);
        vocBookMapper.deleteById(vocBookDO);
        return vocBookConverter.vocBookDO2DeleteBookDTO(vocBookDO);
    }

    @Override
    @OperateLog(dateType = "书籍", operateType = OperateLogConstant.OPERATE_BATCH_DELETE)
    public List<DeleteBookOperateDTO> deleteVocBooks(BatchDeleteCommand command) {
        List<Long> ids = command.getIds().stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());

        List<VocBookDO> vocBookDOS = vocBookMapper.selectByIds(ids);
        for (Long bookid : ids) {
            deleteChapterByBookId(bookid);
        }
        List<DeleteBookOperateDTO> deleteBookOperateDTOS = vocBookConverter.vocBookDOs2DeleteBookDTOs(vocBookDOS);
        vocBookMapper.deleteByIds(ids);
        return deleteBookOperateDTOS;
    }

    private void deleteChapterByBookId(Long bookId) {
        LambdaQueryWrapper<VocChapterDO> vocChapterDOWrapper = new LambdaQueryWrapper<>();
        vocChapterDOWrapper.select(VocChapterDO::getId)
                .eq(VocChapterDO::getBookId,bookId);
        List<Long> chapterIds = vocChapterMapper.selectObjs(vocChapterDOWrapper)
                .stream()
                .map(id -> (Long) id)
                .collect(Collectors.toList());

        if(!chapterIds.isEmpty()){
            BatchDeleteCommand command = new BatchDeleteCommand();
            command.setIds(chapterIds.stream()
                    .map(String::valueOf) // Long转String
                    .collect(Collectors.toList()));
            vocChapterService.deleteChapters(command);
        }
    }
}
